<template>
    <div style="width: 100%; height: 100%;">
        <div>
            <div class="align-stretch tree-panel">
                <org-tree :dept-list.sync="deptList" style="height: 100%;" @node-click="handleNodeClick" />
            </div>
            <div class=" app-container" style="margin-left: 270px;">
                <div class="pageTitle">
                    <div class="pageBtn" style="padding-left: 0;">
                        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
                    </div>
                </div>

                <page-main style="margin: 10px 10px 50px 0;">
                    <el-table ref="orderTable" v-loading="isLoading" class="actionTable" stripe :data="tableData"
                              header-cell-class-name="table-header" style="width: 100%;" border :row-class-name="tableRowClassName">
                        <el-table-column label="用户名" width="120" prop="user_code" />
                        <el-table-column label="真实姓名" width="100" prop="userName" />
                        <el-table-column label="用户状态" width="80" align="center">
                            <template slot-scope="scope">
                                {{ scope.row.user_status|formatStatus }}
                            </template>
                        </el-table-column>
                        <el-table-column label="联系电话" width="120" prop="phone_no" />
                        <el-table-column label="登录次数" width="100" prop="login_times" />
                        <el-table-column label="创建时间" width="200">
                            <template slot-scope="scope">
                                {{ moment(scope.row.gmt_create).format('YYYY-MM-DD HH:mm:ss') }}
                            </template>
                        </el-table-column>
                        <el-table-column label="角色" width="150" prop="roleName" show-overflow-tooltip />
                        <el-table-column label="组织机构名称" width="120" prop="deptName" />
                        <el-table-column label="操作" width="150" fixed="right" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
                                <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </page-main>
            </div>
        </div>

        <el-dialog :title="currentUser.isNew?'添加用户':'修改用户'" :visible.sync="detailVisible" width="700px">
            <el-form ref="form" :model="currentUser" :rules="rules" label-width="120px" size="small">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="所属组织机构">
                            <treeselect v-model="currentUser.dept_id"  clearable="false" :normalizer="normalizer" :options="deptList" placeholder="选择上级部门" @select="orgSelected" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用户名" prop="user_code">
                            <el-input v-model="currentUser.user_code" placeholder="请输入用户名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="真实姓名" prop="userName">
                            <el-input v-model="currentUser.userName" placeholder="请输入真实姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="密码" prop="login_pwd">
                            <el-input v-model="currentUser.login_pwd" placeholder="请输入密码" show-password />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="确认密码" prop="login_pwd2">
                            <el-input v-model="currentUser.login_pwd2" placeholder="请输入确认密码" show-password />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="用户级别" prop="priority">
                            <el-select v-model="currentUser.priority" style="width: 100%;" placeholder="请选择">
                                <el-option
                                    v-for="item in 100"
                                    :key="item"
                                    :label="item"
                                    :value="item" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="用户状态" prop="user_status">
                            <dict-select v-model="currentUser.user_status" style="width: 100%;" dict="dict_UserStatus" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="phone_no">
                            <el-input v-model="currentUser.phone_no" placeholder="请输入联系电话" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="Email" prop="email">
                            <el-input v-model="currentUser.email" placeholder="请输入Email" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="到期时间" prop="gmt_expire">
                            <el-date-picker
                                v-model="currentUser.gmt_expire"
                                style="width: 100%;"
                                :clearable="false"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                placeholder="选择日期" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="角色" prop="role_id">
                            <el-select v-model="currentUser.role_id" style="width: 100%;" clearable placeholder="请选择">
                                <el-option v-for="(item,index) in roleOptions" :key="index" :label="item.role_name" :value="item.role_id">
                                    <span style="float: left;">{{ item.role_name }}
                                        <span style="color: #8492a6; font-size: 13px;">({{ item.description }})</span>
                                    </span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="detailVisible = false">取 消</el-button>
                <el-button size="small" :loading="isLoading" type="primary" @click="handleSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment';
import OrgTree from './OrgTree';
import DictSelect from '@/modules/components/DictSelect';
import {dictFilter} from '@/modules/components/DictSelect/dict-data';
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

import {
    SelectTuserInfo, InsertTuserInfo,
    UpdateTuser, DeleteTuser, SelectAllRole
} from '@/api/userManageApi';

export default {
    name: 'user-manage',
    components: {
        OrgTree, Treeselect ,DictSelect
        // DictSelect,
    },
    filters: {
        formatStatus(value) {
            return dictFilter(value, 'dict_UserStatus');
        }
    },
    props: {},
    data() {

        let validatePassWord = (rule, value, callback) => {
            if (!value) {
                callback(new Error('确认密码不能为空'));
            } else if (value !== this.currentUser.login_pwd) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };

        return {
            isLoading: false,
            tableData: [],
            detailVisible: false,
            currentUser: {},
            rules: {
                user_code: [
                    { required: true, message: '用户名不能为空', trigger: 'blur' }
                ],
                login_pwd: [
                    { required: true, message: '密码不能为空', trigger: 'blur' }
                ],
                login_pwd2: [
                    {required: true, validator: validatePassWord, trigger: 'blur'}
                ],
                user_status: [
                    { required: true, message: '用户名类型不能为空', trigger: 'change' }
                ],
                priority: [
                    { required: true, message: '用户名级别不能为空', trigger: 'change' }
                ],
                role_id: [
                    { required: true, message: '角色不能为空', trigger: 'change' }
                ],
                userName: [
                    { required: true, message: '真实姓名不能为空', trigger: 'change' }
                ],
                gmt_expire: [
                    { required: true, message: '到期时间不能为空', trigger: 'change' }
                ]

            },
            roleOptions: [],
            currentNode: null,
            deptList: []
        };
    },
    computed: {

    },
    watch: {

    },
    created() {

    },
    mounted() {
        this.loadRoleOptions();
        this.loadRemoteData();
    },
    methods: {
        moment,
        tableRowClassName({row, rowIndex}) {
            if (this.detailVisible && this.currentUser.user_id == row.user_id) {
                return 'selected-row';
            }
            return '';
        },
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                isDefaultExpanded: true,
                id: node.dept_id,
                label: node.dept_name,
                children: node.children
            };
        },
        handleNodeClick(data) {
            this.currentNode = data;
            console.log("------------");
            console.log(this.currentNode);
            this.loadRemoteData();
        },

        loadRemoteData() {
            this.isLoading = true;
            let params = this.currentNode &&  {dept_id: this.currentNode.dept_id};
            SelectTuserInfo(params).then(res => {
                this.isLoading = false;
                let result = res.res.UserInfo;
                this.tableData = result;
            }).catch(err => {
                this.isLoading = false;
                console.log(err);
            });
        },
        orgSelected(node) {
            this.currentUser.dept_name = node.name;
        },
        handleAdd() {

            this.currentUser = {
                isNew: true,
                dept_id: this.currentNode ? this.currentNode.dept_id : undefined,
                dept_name: this.currentNode ? this.currentNode.dept_name : '主控中心',
                expire_time: '2120-12-31',
                name: '',
                phone_no: '',
                email: ''
            };

            this.$nextTick(() => {
                this.$refs['form'] && this.$refs['form'].clearValidate();
            });

            this.detailVisible = true;
        },
        handleEdit(item) {
            this.currentUser = {
                dept_id: item.dept_id,
                dept_name: item.dept_name,
                user_code: item.user_code,
                userName: item.userName,
                login_pwd: item.login_pwd,
                login_pwd2: item.login_pwd,
                priority: item.priority,
                user_status: item.user_status,
                phone_no: item.phone_no,
                email: item.email,
                role_id: item.role_id,
                user_id: item.user_id,
                gmt_expire: moment(item.expire_time).format('YYYY-MM-DD')
            };
            this.$nextTick(() => {
                this.$refs['form'] && this.$refs['form'].clearValidate();
            });
            this.detailVisible = true;
        },
        handleDelete(item) {
            this.$confirm('确定要删除此用户吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                this.isLoading = true;
                DeleteTuser({
                    user_id: item.user_id
                }).then(res => {
                    this.isLoading = false;
                    this.$message.success('删除成功');
                    this.loadRemoteData();
                }).catch(err => {
                    this.isLoading = false;
                    console.log(err);
                });

            }).catch(err => {
                console.log(err);
            });
        },
        handleSubmit() {
            if (this.clickTooFast()) return;
            this.$refs['form'].validate(valid => {
                if (valid) {
                    this.isLoading = true;

                    // this.currentUser.role_id = this.currentUser.role_array.join(",");

                    if (this.currentUser.isNew) {
                        InsertTuserInfo(this.currentUser).then(res => {
                            this.$message.success('添加成功');
                            this.loadRemoteData();
                            this.detailVisible = false;
                            this.isLoading = false;
                        }).catch(err => {
                            this.isLoading = false;
                            console.log(err);
                        });
                    } else {
                        UpdateTuser(this.currentUser).then(res => {
                            this.$message.success('修改成功');
                            this.loadRemoteData();
                            this.detailVisible = false;
                            this.isLoading = false;
                        }).catch(err => {
                            this.isLoading = false;
                            console.log(err);
                        });
                    }
                }
            });
        },
        loadRoleOptions() {
            this.roleOptions = [];
            SelectAllRole().then(res => {
                this.roleOptions = res.res.SelectAllRole;
            }).catch(err => {
                console.log(err);
            });
        }

    }
};
</script>

<style scoped>

.table-header {
    background-color: #f8f8f8 !important;
}
/deep/
.el-table td {
    padding: 5px 0 !important;
}
/deep/
.el-button--text {
    padding: 5px 0;
}
/deep/
.el-dialog__body {
    padding: 10px 20px;
}
/deep/
.el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #dcdfe6;
}
</style>

<style lang="scss" scoped>

.table-header {
    background-color: #f8f8f8 !important;
}
.el-table ::v-deep td {
    padding: 5px 0 !important;
}
.tree-panel {
    margin-left: var(--real-sidebar-width);
    height: calc(100% - 120px);
    position: fixed;
    z-index: 100;
    left: 0;
    width: 260px;
    padding-left: 5px;
    padding-top: 5px;
    background: #fbfbfb;
    border: 1px solid #e5e5e5;
    margin-right: 10px;
}
</style>
